let { projectRootPath } = require("./util/index.js");
// 获取主 app
let { mainApp } = require(`${projectRootPath}/app/index.js`);
let { noNeedTokenUrlList } = require(`${projectRootPath}/config/index.js`);
let { verifyToken } = require(`${projectRootPath}/util/jwt/index.js`);
let { getUserByUsername } = require(`${projectRootPath}/service/user/index.js`);
let config = require(`${projectRootPath}/config/index.js`);
mainApp.use(async (req, res, next) => {
  try {
    let originUrl = req.originalUrl;
    if (noNeedTokenUrlList.includes(originUrl)) {
      return next();
    }
    let token = req.headers["x-token"];
    let user = verifyToken(token);
    if (user.username === config.admin.username) {
      return next();
    }
    let dbUser = await getUserByUsername(user);
    dbUser = dbUser.list[0];

    if (dbUser.token === token) {
      return next();
    } else {
      return res.send({ data: {}, message: "token 过期", code: 50008 });
    }
  } catch (error) {
    return next(error);
  }
});
// 设置静态文件夹
mainApp.use("/static", require("express").static(`${projectRootPath}/static`));
// 加载 pc 相关的接口
mainApp.use("/pc", require(`${projectRootPath}/controller/pc/index`));
// 加载微信小程序的接口
mainApp.use("/wechat", require(`${projectRootPath}/controller/wechat/index`));
let { port } = require(`${projectRootPath}/config/index.js`);
mainApp.listen(port, () => {
  console.log(`启动: ${port}`);
});
